package com.example.myapplication;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

public class RegisterActivity extends AppCompatActivity {
    private static final String TAG = "RegisterActivity";

    // 控件声明
    private TextView tvTitle;
    private EditText etRegUsername;
    private EditText etRegPwd;
    private EditText etRegConfirmPwd;
    private ImageView ivTogglePwd1;
    private ImageView ivTogglePwd2;
    private CheckBox cbAgreePrivacy;
    private TextView tvPrivacy;
    private LinearLayout layoutPrivacy;
    private Button btnDoRegister;
    private Button btnBackToLogin;

    // 密码可见性状态标记
    private boolean isPwd1Visible = false;
    private boolean isPwd2Visible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: 注册页面创建");
        setContentView(R.layout.activity_register);

        // 初始化所有控件
        initViews();
        // 设置“隐私协议”超链接样式
        setupPrivacyTextStyle();
        // 配置所有交互监听
        setupAllListeners();
    }

    /**
     * 初始化所有控件（绑定布局ID）
     */
    private void initViews() {
        tvTitle = findViewById(R.id.tv_title);
        etRegUsername = findViewById(R.id.et_register_username);
        etRegPwd = findViewById(R.id.et_register_password);
        etRegConfirmPwd = findViewById(R.id.et_register_confirm_pwd);
        ivTogglePwd1 = findViewById(R.id.iv_toggle_pwd1);
        ivTogglePwd2 = findViewById(R.id.iv_toggle_pwd2);
        cbAgreePrivacy = findViewById(R.id.cb_agree_privacy);
        tvPrivacy = findViewById(R.id.tv_privacy);
        layoutPrivacy = findViewById(R.id.layout_privacy);
        btnDoRegister = findViewById(R.id.btn_do_register);
        btnBackToLogin = findViewById(R.id.btn_back_to_login);
    }

    /**
     * 设置“隐私协议”文字的超链接样式（蓝色+下划线+点击提示）
     */
    private void setupPrivacyTextStyle() {
        String fullText = tvPrivacy.getText().toString();
        if (TextUtils.isEmpty(fullText)) {
            fullText = "我已同意隐私协议";
            tvPrivacy.setText(fullText);
        }

        SpannableString spannable = new SpannableString(fullText);
        String agreeText = "我已同意";
        String privacyText = "隐私协议";

        // 定位“隐私协议”在完整文字中的起始/结束位置
        int start = agreeText.length();
        int end = fullText.length();

        // 1. 设置“隐私协议”为蓝色
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(
                ContextCompat.getColor(this, android.R.color.holo_blue_light)
        );
        spannable.setSpan(colorSpan, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        // 2. 设置“隐私协议”为下划线
        UnderlineSpan underlineSpan = new UnderlineSpan();
        spannable.setSpan(underlineSpan, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        // 3. 设置“隐私协议”点击事件（仅Toast提示，不跳转）
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Toast.makeText(RegisterActivity.this, "隐私协议内容（模拟链接）", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(true); // 保持下划线
                ds.bgColor = ContextCompat.getColor(RegisterActivity.this, android.R.color.transparent); // 透明背景，避免点击高亮
            }
        };
        spannable.setSpan(clickableSpan, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        // 应用样式并启用点击
        tvPrivacy.setText(spannable);
        tvPrivacy.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * 配置所有控件的交互监听
     */
    private void setupAllListeners() {
        // 「返回登录」按钮点击：关闭当前页面
        btnBackToLogin.setOnClickListener(v -> finish());

        // 用户名输入框：焦点变化时切换背景
        etRegUsername.setOnFocusChangeListener((v, hasFocus) -> {
            etRegUsername.setBackgroundResource(
                    hasFocus ? R.drawable.edittext_border_focused : R.drawable.edittext_bg
            );
        });

        // 密码输入框：焦点变化时切换背景
        etRegPwd.setOnFocusChangeListener((v, hasFocus) -> {
            etRegPwd.setBackgroundResource(
                    hasFocus ? R.drawable.edittext_border_focused : R.drawable.edittext_bg
            );
        });

        // 确认密码输入框：焦点变化时切换背景
        etRegConfirmPwd.setOnFocusChangeListener((v, hasFocus) -> {
            etRegConfirmPwd.setBackgroundResource(
                    hasFocus ? R.drawable.edittext_border_focused : R.drawable.edittext_bg
            );
        });

        // 密码可见性切换：点击图标切换明文/密文
        ivTogglePwd1.setOnClickListener(v -> togglePasswordVisibility(etRegPwd, ivTogglePwd1, 1));
        ivTogglePwd2.setOnClickListener(v -> togglePasswordVisibility(etRegConfirmPwd, ivTogglePwd2, 2));

        // 隐私协议复选框：勾选状态变化时，更新注册按钮状态
        cbAgreePrivacy.setOnCheckedChangeListener((buttonView, isChecked) -> {
            updateRegisterButtonState();
        });

        // 输入文本变化监听：实时检查输入合法性，更新注册按钮状态
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                updateRegisterButtonState();
            }
        };
        etRegUsername.addTextChangedListener(textWatcher);
        etRegPwd.addTextChangedListener(textWatcher);
        etRegConfirmPwd.addTextChangedListener(textWatcher);

        // 「注册」按钮点击：执行注册逻辑
        btnDoRegister.setOnClickListener(v -> handleRegister());
    }

    /**
     * 切换密码可见性（明文/密文）
     */
    private void togglePasswordVisibility(EditText editText, ImageView imageView, int pwdType) {
        if (pwdType == 1) {
            isPwd1Visible = !isPwd1Visible;
            editText.setInputType(isPwd1Visible ?
                    (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) :
                    (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
            imageView.setImageResource(isPwd1Visible ? R.drawable.ic_visibility : R.drawable.ic_visibility_off);
        } else {
            isPwd2Visible = !isPwd2Visible;
            editText.setInputType(isPwd2Visible ?
                    (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) :
                    (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
            imageView.setImageResource(isPwd2Visible ? R.drawable.ic_visibility : R.drawable.ic_visibility_off);
        }
        editText.setSelection(editText.getText().length()); // 保持光标在末尾
    }

    /**
     * 更新注册按钮的“启用状态”和“背景色”
     */
    private void updateRegisterButtonState() {
        String username = etRegUsername.getText().toString().trim();
        String pwd = etRegPwd.getText().toString().trim();
        String confirmPwd = etRegConfirmPwd.getText().toString().trim();
        boolean isAgreePrivacy = cbAgreePrivacy.isChecked();

        // 按钮启用条件：用户名有效、密码有效、确认密码有效、已同意隐私协议
        boolean isEnabled = !TextUtils.isEmpty(username) && username.length() >= 3
                && !TextUtils.isEmpty(pwd) && pwd.length() >= 6
                && !TextUtils.isEmpty(confirmPwd)
                && isAgreePrivacy;

        btnDoRegister.setEnabled(isEnabled);
        // 使用ContextCompat确保Android版本兼容性
        btnDoRegister.setBackgroundTintList(ContextCompat.getColorStateList(
                this,
                isEnabled ? R.color.purple_500 : android.R.color.darker_gray
        ));
    }

    /**
     * 处理注册逻辑（输入验证 + 模拟网络请求）
     */
    private void handleRegister() {
        // 双重验证：必须勾选隐私协议
        if (!cbAgreePrivacy.isChecked()) {
            Toast.makeText(this, "请先同意隐私协议", Toast.LENGTH_SHORT).show();
            return;
        }

        String username = etRegUsername.getText().toString().trim();
        String pwd = etRegPwd.getText().toString().trim();
        String confirmPwd = etRegConfirmPwd.getText().toString().trim();

        // 验证输入合法性
        if (!validateInput(username, pwd, confirmPwd)) {
            return;
        }

        // 显示注册进度弹窗
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在注册...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        // 模拟网络请求（2秒后完成）
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            progressDialog.dismiss();
            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
            finish(); // 注册成功后关闭当前页面，返回登录页
        }, 2000);
    }

    /**
     * 验证输入合法性（用户名、密码、确认密码）
     */
    private boolean validateInput(String username, String pwd, String confirmPwd) {
        if (username.length() < 3) {
            Toast.makeText(this, "用户名长度不能少于3位", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (pwd.length() < 6) {
            Toast.makeText(this, "密码长度不能少于6位", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!pwd.equals(confirmPwd)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    // 生命周期日志（可选，用于调试）
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: 页面可见");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: 页面可交互");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: 页面失去焦点");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: 页面不可见");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: 页面销毁");
    }
}